#!/usr/bin/env python
'''
Example of (almost) all widgets, that you can use in PySimpleGUI.
'''

import PySimpleGUI as sg
from pwlf_regression import createNozzleMap

sg.theme('Dark Red')
# sg.set_options(text_color='black', background_color='#A6B2BE', text_element_background_color='#A6B2BE')
# ------ Menu Definition ------ #
# menu_def = [['&File', ['&Open', '&Save', 'E&xit', 'Properties']],
#             ['&Edit', ['Paste', ['Special', 'Normal', ], 'Undo'], ],
#             ['&Help', '&About...'], ]

# # ------ Column Definition ------ #
# column1 = [[sg.Text('Column 1', justification='center', size=(10, 1))],
#            [sg.Spin(values=('Spin Box 1', '2', '3'),
#                     initial_value='Spin Box 1')],
#            [sg.Spin(values=['Spin Box 1', '2', '3'],
#                     initial_value='Spin Box 2')],
#            [sg.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 3')]]

layout = [
    #[sg.Menu(menu_def, tearoff=True)],
    [sg.Text('相机喷阀映射文件生成器', size=(
        30, 1), justification='center', font=("Helvetica", 25), relief=sg.RELIEF_RIDGE)],
    [sg.Frame(layout=[
        [   sg.Radio('4,096px',  "pixelSize",default=False,size=(10, 1)),
            sg.Radio('8,192px', "pixelSize", default=False,size=(10, 1)),
            sg.Radio('7680px', "pixelSize", default=False,size=(10, 1)),
            sg.Radio('3840px', "pixelSize", default=False,size=(10, 1)),
            sg.Radio('3294px', "pixelSize", default=True,size=(10, 1))
        ]], title='相机分辨率', relief=sg.RELIEF_SUNKEN, tooltip='Use these to set flags')],
    [sg.Text('其他分辨率方案')],
    [sg.InputText('')],

    [sg.Text('喷阀总数,如160')],
    [sg.InputText('160')],
    [sg.Text('输入对应阀序号，以英文输入法","间隔。如：1,20,...')],
    [sg.InputText('')],
    [sg.Text('输入阀对应图片坐标，以英文输入法","间隔。如：5029,4441,...')],
    [sg.InputText('')],
    [sg.Text('_' * 80)],
    [sg.Frame(layout=[
    [   sg.Radio('线性拟合',  "curzeType",default=True,size=(10, 1)),
            sg.Radio('分段拟合', "curzeType", default=False,size=(10, 1)),
    ]], title='拟合方式', relief=sg.RELIEF_SUNKEN, tooltip='Use these to set flags')],
    [sg.Text('不可用阀序号')],
    [sg.InputText('0')],
    [sg.Text('保存路径', justification=''),
     sg.InputText('Default Folder'), sg.FolderBrowse()],
    
    [sg.Text('_' * 80)],
    [sg.Text('--------------------------喷射映射文件微调--------------------------')],
    [sg.Text('选择喷射映射文件')],
    [sg.Text('选择文件', justification=''),
     sg.InputText('Default File'), sg.FileBrowse()],
    [sg.Text('起始喷阀序号')],
        [sg.InputText('0')],
    [sg.Text('截至喷阀序号')],
        [sg.InputText('0')],
    [sg.Text('左移或者右移位数X,正:区间段喷阀序号增加X,负:区间段喷阀序号减少X')],
        [sg.InputText('0')],

    [sg.Submit(tooltip='Click to submit this form'), sg.Cancel()]]

# layout3= [[sg.Text('Last Job', size=(10,1)),sg.Input('',key='eLastJ')],
#            [sg.Text('From Date', size=(10,1)),sg.Input('',key='eJFdt')],
#            [sg.Text('To Date', size=(10,1)),sg.Input('',key='eJTdt')],
#            [sg.Text('Company Name', size=(10,1)),sg.Input('',key='eLJcmpy')],
#           [sg.Button('Save Experience Details')]]

# tabgrp = [[sg.TabGroup([[sg.Tab('Personal Details', layout, border_width =10, 
#                                 tooltip='Personal details'),
#                     sg.Tab('Experience', layout3,title_color='Black',
#                            tooltip='Enter  your Lsst job experience')]], tab_location='centertop',
#                        title_color='Red',  border_width=5)]]  




window = sg.Window('喷阀坐标工具', layout)

event, values = window.read(close=True)
# sg.popup('Title',
#         'The results of the window.',
#         'The button clicked was "{}"'.format(event),
#         'The values are', values)
if(event == "Submit"):

    if(values[13] == 'Default File'):

        if(len(values[6])==0 or len(values[7])==0):
            sg.popup("喷阀数量或像素点为空")
            exit()
        nuzzleSeq = values[7].split(',')
        nuzzleSeq = list(map(int,nuzzleSeq))
        pixelSeq = values[8].split(',')
        pixelSeq = list(map(int,pixelSeq))

        # if(len(nuzzleSeq) != len(pixelSeq)):
        #     sg.popup("输入喷阀数量和像素点数量不一致，请重新输入")
        #     exit()

        if(values[0] == True):
            nozzleMap = 4096
        elif(values[1] == True):
            nozzleMap = 8192
        elif(values[2] == True):
            nozzleMap = 7680
        elif(values[3] == True):
            nozzleMap = 3840
        else:
            nozzleMap = 3294
        if values[5] != '':
            nozzleMap = int(values[5])    
        print(nozzleMap)
        if(values[9] == True):
            curzeType = True
        elif(values[10] == True):
            curzeType = False
        else:
            curzeType = False
        nuzzleNumTotal = values[6]
        badNozzle = values[11]
        savePath = values[12]

        status = createNozzleMap(pixelSeq,nuzzleSeq,int(nuzzleNumTotal),savePath,nozzleMap,curzeType,int(badNozzle))
        if(status == 1):
            sg.popup('生成成功!')
        else:
            sg.popup('生成失败!')
    else:
        # print(values[13])
        # print(values[14])
        # print(int(values[15]))
        maxNozzle = 0
        totalPixel = 0
        with open(values[13],'r') as f:
            for line in f:
                maps = line.split(' ')
                lastNozzle = maps[-1]
                totalPixel = len(maps)
                
                for idx,val in enumerate(maps):
                    if(val != ''):
                        if (int(val) >= (int(values[14])-1) and int(val) <= (int(values[15])-1) ):
                            tmp = int(val) + int(values[16])
                            if(tmp <=0):
                                tmp = 0
                            elif(tmp >= int(values[6])-1):
                                tmp = int(values[6])-1
                            maps[idx] = tmp
        saveNewFile = values[13].split('.')[-2]

        if saveNewFile != '':

            with open(saveNewFile+'_new.txt','wt') as ff:
                for val in maps:
                    ff.write(str(val))
                    ff.write(" ")
                
        sg.popup('微调成功!')

    # sg.popup('Title',
    #     'The results of the window.',
    #     'The button clicked was "{}"'.format(event),
    #     'The values are', values)


